package org.example.common.config;

import cn.dev33.satoken.exception.NotLoginException;
import jakarta.validation.ConstraintViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

@RestControllerAdvice  // 添加这个关键注解
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleException(MethodArgumentNotValidException e) {

        return Result.fail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(value = {ConstraintViolationException.class})
    public Result handleException(ConstraintViolationException e) {
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleException(DuplicateKeyException e) {
        return Result.error(400, "数据重复,请检查");
    }

    @ExceptionHandler(SQLException.class)
    public Result handleSQLException(SQLException e){
        return Result.error(400, "数据操作失败，请检查:"+e.getMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public Result handleException(NotLoginException e) {
        return Result.error(401, "登陆失效，请重新登录");
    }

    @ExceptionHandler(value = Exception.class)
    public Result handleException(Exception e) {
        return Result.fail(e.getLocalizedMessage());
    }


}
